<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button icon="el-icon-arrow-right" circle @click="showTree=!showTree" />
      <el-input v-model="listQuery.name" placeholder="资源名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <div style="text-align: right;">
        <el-button icon="el-icon-edit" circle type="primary" style="float: right;" @click="showColumnDialog" />
      </div>
      <el-dialog :visible.sync="dialogVisible">
        <el-checkbox-group v-model="selectedColumns">
          <el-checkbox v-for="column in Object.keys(columnVisibilityMap)" :key="column" :label="column" :checked="columnVisibilityMap[column]">{{ column }}</el-checkbox>        </el-checkbox-group>
        <el-button type="primary" @click="applySelectedColumns">应用</el-button>
      </el-dialog>
    </div>
    <el-container>
      <transition name="el-zoom-in-center">
        <el-aside v-if="showTree" width="200px" class="transition-box" style="background-color: rgb(238, 241, 246);">
          <meau @nodeClicked="handleNodeClicked" @nodeNameClicked="handleNodeNames" />
        </el-aside>
      </transition>
      <el-main>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          增加
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-refresh" @click="handleFilter">
          刷新
        </el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-copy-document" @click="handleCopyList">
          复制
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleDeleteList">
          删除
        </el-button>
        <el-table
          :key="tableKey"
          v-model="selection"
          v-loading="loading"
          :data="fiterList"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column v-if="columnVisibilityMap['Index']" label="index" prop="index" sortable align="center" width="100" :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.index.toString() }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['name']" label="资源名称" width="110px" sortable align="center">
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['ParentNode']" prop="parentNode" label="父节点" sortable width="150px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.parentNode }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['SubSystem']" prop="subSystem" label="子系统" sortable min-width="150px">
            <template slot-scope="{row}">
              <span>{{ row.subSystem }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['Api']" prop="Api" label="Api" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.api }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['ResourceType']" prop="resourceType" label="资源类型" width="80px">
            <template slot-scope="{row}">
              <span>{{ row.resourceType }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['OpenImg']" prop="openImg" label="打开图标" align="center" width="95">
            <template slot-scope="{row}">
              <span>{{ row.openImg }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['CloseImg']" prop="closeImg" label="关闭图标" class-name="status-col" width="100">
            <template slot-scope="{row}">
              <span>{{ row.closeImg }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columnVisibilityMap['Actions']" label="操作" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-button v-if="row.status!=='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
              <el-button type="primary" size="mini" @click="handleCopy(row.id)">
                复制
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />
      </el-main>
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 600px; margin-left:50px;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="资源名称" prop="name" :inline="true">
                <el-input v-model="temp.name" />
              </el-form-item>
              <el-form-item label="Api" prop="api">
                <el-input v-model="temp.api" />
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="temp.remark" :autosize="{ minRows: 1, maxRows: 3}" type="textarea" placeholder="Please input" />
              </el-form-item>
              <el-form-item label="打开图标" prop="openImg">
                <el-input v-model="temp.openImg" />
              </el-form-item>
              <el-form-item v-model="temp.subSystemId" label="子系统" prop="subSystemId">
                <el-select v-model="temp.subSystemId" placeholder="Select">
                  <el-option v-for="(value, key) in subSystemOptions" :key="value" :label="key" :value="value" />
                </el-select>
              </el-form-item>
              <el-form-item v-model="temp.leaf" label="是否叶子节点">
                <el-radio v-model="temp.leaf" label="1">是</el-radio>
                <el-radio v-model="temp.leaf" label="2">否</el-radio>
              </el-form-item>
              <el-form-item v-model="temp.isHidden" label="是否隐藏">
                <el-radio v-model="temp.isHidden" label="1">是</el-radio>
                <el-radio v-model="temp.isHidden" label="2">否</el-radio>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">Confirm</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="URL" prop="url">
                <el-input v-model="temp.url" />
              </el-form-item>
              <el-form-item :readonly="isUpdate" label="资源编号" prop="id">
                <el-input v-model="temp.id" />
              </el-form-item>
              <el-form-item label="顺序编号" prop="id">
                <el-input v-model="temp.orderIndex" />
              </el-form-item>
              <el-form-item label="关闭图标" prop="closeImg">
                <el-input v-model="temp.closeImg" />
              </el-form-item>
              <el-form-item v-model="temp.parentId" label="父亲节点" prop="parentId">
                <el-select v-model="temp.parentId" placeholder="Select">
                  <el-option v-for="(value, key) in parentNodeOptions" :key="value" :label="key" :value="value" />                </el-select>
              </el-form-item>
              <el-form-item v-model="temp.resourceType" label="资源类型">
                <el-radio v-model="temp.resourceType" label="1">菜单</el-radio>
                <el-radio v-model="temp.resourceType" label="2">按钮</el-radio>
              </el-form-item>
              <el-form-item>
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">Cancel</el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">Confirm</el-button>
          </div>
        </el-form>
      </el-dialog>
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
        </span>
      </el-dialog>
    </el-container>
  </div>
</template>
<style>
.left-aside {
  background-color: #f0f0f0;
  padding: 20px;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  margin-bottom: 10px;
}
</style>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import loading from 'element-ui/packages/loading' // secondary package based on el-pagination
import Meau from '@/views/resourceManagement/components/meau.vue'
import { copy, deleteList, getAll, getOptions, getSubsystem } from '@/api/resource'
import { updateResource } from '@/action/resourceManagement/resourceUpdateAction'
import { addResource } from '@/action/resourceManagement/resourceAddAction'

// arr to obj, such as { CN : "China", US : "USA" }

export default {
  name: 'ResourceManagement',
  components: { Meau, Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      fiterList: [],
      showTree: false,
      isUpdate: true,
      subSystemOptions: [],
      parentNodeOptions: [],
      selectedRows: [],
      dataForm: {
        remark: '',
        url: '',
        api: '',
        name: '',
        subSystemId: '',
        parentId: '',
        orderIndex: '',
        leaf: '',
        isHidden: '',
        resourceType: '',
        resourceId: '',
        openImg: '',
        closeImg: ''
      },
      rules: {
        url: [{ required: true, message: 'Please input URL', trigger: 'blur' }],
        api: [{ required: true, message: 'Please input API', trigger: 'blur' }],
        name: [{ required: true, message: 'Please input Resource Name', trigger: 'blur' }],
        subSystemId: [{ required: true, message: 'Please input Son System', trigger: 'blur' }],
        parentId: [{ required: true, message: 'Please input Parent Node', trigger: 'blur' }],
        leaf: [{ required: true, message: 'Please input Is Leaf Node', trigger: 'blur' }],
        isHidden: [{ required: true, message: 'Please input Is Hidden', trigger: 'blur' }],
        resourceType: [{ required: true, message: 'Please input Resource Type', trigger: 'blur' }],
        resourceId: [{ required: true, message: 'Please input Resource ID', trigger: 'blur' }],
        openImg: [{ required: true, message: 'Please input Open Pic', trigger: 'blur' }],
        closeImg: [{ required: true, message: 'Please input Close Pic', trigger: 'blur' }]
      },
      loading: false,
      columnVisibilityMap: {
        'Index': true,
        'ParentNode': true,
        'SubSystem': true,
        'Api': true,
        'ResourceType': true,
        'OpenImg': true,
        'CloseImg': true,
        'Actions': true,
        'name': true
      },
      showColumns: ['Index', 'ParentNode', 'name', 'SubSystem', 'Author', 'Api', 'ResourceType', 'OpenImg', 'CloseImg', 'Actions'],
      dialogVisible: false,
      selectedColumns: {
        'Index': true,
        'ParentNode': true,
        'SubSystem': true,
        'Api': true,
        'name': true,
        'ResourceType': true,
        'OpenImg': true,
        'CloseImg': true,
        'Actions': true
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        name: '',
        page: 1,
        pageSize: 20
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: true,
      selection: [],
      temp: {
        id: undefined,
        remark: '',
        url: '',
        api: '',
        orderIndex: '',
        name: '',
        subSystemId: '',
        parentId: '',
        leaf: '',
        resourceType: '',
        isHidden: '',
        openImg: '',
        closeImg: ''
      },
      ids: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: []

    }
  },
  computed: {
    // eslint-disable-next-line vue/no-dupe-keys
    loading() {
      return loading
    }

  },
  created() {
    this.getList()
    this.getOptions()
  },
  methods: {
    copy,
    deleteList,
    showColumnDialog() {
      this.selectedColumns = this.showColumns.filter(column => this.columnVisibilityMap[column])
      this.dialogVisible = true
    },
    applySelectedColumns() {
      this.showColumns = this.selectedColumns.slice()
      for (const column in this.columnVisibilityMap) {
        this.columnVisibilityMap[column] = false
      }
      for (const column of this.selectedColumns) {
        this.columnVisibilityMap[column] = true
      }
      this.dialogVisible = false
    },
    getList() {
      this.listLoading = true
      console.log(this.listQuery)
      getAll(this.listQuery).then(response => {
        this.list = response.records
        this.list.map((item, index) => {
          item.index = index + 1
          item.resourceType = item.resourceType === '1' ? '菜单' : '按钮'
          item.subSystem = item.subSystem == null ? 'No Data' : item.subSystem
          item.parentNode = item.parentNode == null ? 'No Data' : item.parentNode
        })
        this.fiterList = this.list
        this.total = response.total
      })
    },
    handleNodeClicked(id) {
      const filteredNames = [id]
      console.log(filteredNames)
      this.fiterList = this.list.filter(item => filteredNames.includes(item.parentNode))
    },
    handleNodeNames(names) {
      console.log(names)
      this.fiterList = this.list.filter(item => {
        const isIncluded = names.includes(item.parentNode)
        console.log(item.parentNode)
        console.log(`Item ${item.id} is included: ${isIncluded}`)
        return isIncluded
      })
      console.log(this.list)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleCopy(id) {
      this.ids = []
      this.ids.push(id)
      copy(this.ids).then(response => {
        this.$notify({
          message: '复制成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleCopyList() {
      if (this.ids.length === 0) {
        this.$message({
          message: '请选择要复制的资源',
          type: 'warning'
        })
      } else {
        copy(this.ids).then(response => {
          this.$notify({
            title: '成功',
            message: '复制成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.ids = selection.map(row => row.id)
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        remark: '',
        orderIndex: '',
        url: '',
        api: '',
        name: '',
        subSystem: '',
        parentNode: '',
        leaf: '',
        resourceType: '',
        isHidden: ''
      }
    },
    getOptions() {
      getSubsystem().then(response => {
        console.log(response)
        this.subSystemOptions = response
      })
      getOptions().then(response => {
        console.log(response)
        this.parentNodeOptions = response
        console.log(this.parentNodeOptions)
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleNodeClick() {

    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addResource(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateResource(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.isUpdate = true
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ids = []
        this.ids.push(row.id)
        deleteList(this.ids).then(response => {
          console.log(response)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteList() {
      if (this.ids.length === 0) {
        this.$message({
          message: '请选择要删除的项',
          type: 'warning'
        })
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteList(this.ids).then(response => {
            console.log(response)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
